#include "mainwindow.h"
#include "ui_mainwindow.h"
#include<QTcpServer>
#include<QTcpSocket>
#include<QString>
#include<QLabel>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    //这个放最下面会程序异常结束
    this->setWindowTitle("客户端");
    
    
    connection_status = new QLabel;
    ui->statusBar->addWidget(connection_status);
    //状态栏标签

    //TCP客户端

    ui->port->setText("8899");
    //端口号
    ui->ip->setText("127.0.0.1");



    //客户端服务器不用创建，直接创套接字

    socket=new QTcpSocket(this);

    connect(socket,&QTcpSocket::readyRead,this,[=](){
        QByteArray data=socket->readAll();
        ui->history->append("server:"+data);
    });
    connect(socket,&QTcpSocket::disconnected,this,[=](){
        connection_status->setText("连接断开!");
        socket->close();
        socket->deleteLater();
        ui->connecttosever->setDisabled(false);
        ui->disconnect->setEnabled(false);
    });
    connect(socket,&QTcpSocket::connected,this,[=](){
        connection_status->setText("连接成功!");
        ui->connecttosever->setDisabled(true);
        ui->disconnect->setEnabled(true);
    });




}

MainWindow::~MainWindow()
{
    delete ui;
}



void MainWindow::on_pushButton_clicked()
{
    QString str=ui->message->toPlainText();

    socket->write(str.toUtf8());
    //qstring转qbytearray
    ui->history->append("client:"+str);
}

void MainWindow::on_connecttosever_clicked()
{
    QString IP=ui->ip->text();
    unsigned short port=ui->port->text().toUShort();
    socket->connectToHost(QHostAddress(IP),port);
}

void MainWindow::on_disconnect_clicked()
{
    socket->close();
    ui->connecttosever->setDisabled(false);
    ui->disconnect->setEnabled(false);
}
